package io.renren.task;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import io.renren.entity.TApiDeployinfoEntity;
import io.renren.service.TApiDeployinfoService;
import io.renren.utils.RRException;

@Component("refreshEKBTokenTask")
public class RefreshEKBTokenTask {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Value("${apirefreshtokenurl}")
	private String apiRefreshTokenUrl;
	@Autowired
	private TApiDeployinfoService tApiDeployinfoService;
	public void refresh(String ip){
		// 刷新token
		try {
			StringBuffer buffer=null;  
	        try{  							
	        	URL url=new URL(apiRefreshTokenUrl+"refreshtoken?realip="+ip);  
		        HttpURLConnection conn=(HttpURLConnection)url.openConnection();  
		        conn.setDoOutput(true);  
		        conn.setDoInput(true);  
		        conn.setRequestMethod("GET");  
		        conn.connect();  
		        //读取服务器端返回的内容  
		        InputStream is=conn.getInputStream();  
		        InputStreamReader isr=new InputStreamReader(is,"utf-8");  
		        BufferedReader br=new BufferedReader(isr);  
		        buffer=new StringBuffer();  
		        String line=null;  
		        while((line=br.readLine())!=null){  
		            buffer.append(line);  
		        }  
	        }catch(Exception e){  
	            e.printStackTrace();  
	        }  
	        String res = buffer.toString();
	        logger.info("ip地址为:"+ip+",刷新token 结果为:" + res);
	        if(res.indexOf("405")>=0) {
	        	throw new RRException("授权失败，请检测验证码是否正确",500);
	        }
		} catch (Exception e) {
			
			if(e instanceof RRException)
				throw (RRException)e;
			else {
				logger.info("刷新token 失败:" + e.getMessage());
			}
			/*throw new RRException(e.getMessage(),500);*/
		}
	}
	public void refresh(){
		// 刷新token
		TApiDeployinfoEntity curinfo = tApiDeployinfoService.queryObject(2);
		List<TApiDeployinfoEntity> deployInfo = tApiDeployinfoService.queryAll();
		if(deployInfo != null) {
			for(TApiDeployinfoEntity info :deployInfo) {
				refresh(info.getIp());
			}
		}
	}
}
